package client.comm.baoding.fragment

import android.content.Intent
import android.graphics.Color
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.core.view.ViewCompat
import androidx.core.view.children
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import androidx.viewpager.widget.ViewPager
import client.comm.baoding.R
import client.comm.baoding.adapter.page.CateGoodsPage2Adapter
import client.comm.baoding.adapter.NewSyAdapter
import client.comm.baoding.adapter.SyPagingHeader2Adapter
import client.comm.baoding.api.bean.CateGoods
import client.comm.baoding.api.bean.GoodsIndex
import client.comm.baoding.databinding.FragmentTabone2Binding
import client.comm.baoding.databinding.LayoutCatetabItem2Binding
import client.comm.baoding.ui.SearchActivity
import client.comm.baoding.ui.vm.MainViewModel
import client.comm.commlib.base.BaseFragment
import client.comm.commlib.dipToPx
import client.comm.commlib.toast.toast
import client.comm.commlib.utils.Util
import client.comm.octfdsmall.widget.MyScrollview1
import kotlinx.coroutines.launch

class TabOne2Fragment : BaseFragment<FragmentTabone2Binding, MainViewModel>() {

    override fun getViewId(): Int {
        return R.layout.fragment_tabone2
    }

    val adapter2: NewSyAdapter by lazy {
        NewSyAdapter(requireContext(), mImgLoader).apply {

            refreshLoading = {
//                if (itemCount == 0) {
//                    binding.emptyLayout2.errorType = EmptyLayout.NETWORK_LOADING
//                }
            }
            refreshNotLoading = {
                binding.refreshLayout2.isRefreshing = false
//                if (itemCount == 0) {
//                    binding.emptyLayout2.errorType = EmptyLayout.NODATA
//                } else {
//                    binding.emptyLayout2.visibility = View.GONE
//                }
            }
            refreshError = {
                if (itemCount == 0)
//                    binding.emptyLayout2.errorType = EmptyLayout.NETWORK_ERROR
                toast((it).error.message)
            }

        }
    }

    val headerAdapter2 by lazy {
        SyPagingHeader2Adapter(mImgLoader, 3, requireContext()).apply {

        }
    }


    lateinit var pageAdapter2: CateGoodsPage2Adapter


    override fun initViewModel(): MainViewModel = createViewModel()

    override fun initWidget() {
        binding.statusBar.post {
            val h = Util.getStatusBarHeight(requireContext())
            val p = binding.statusBar.layoutParams
            p.height = h
            binding.statusBar.layoutParams = p
            Util.setBg(resources!!.getColor(R.color.main_color), requireActivity().window)
            val controller = ViewCompat.getWindowInsetsController(binding.root)
            controller?.isAppearanceLightStatusBars = true
        }
        binding.event = this
        binding.recyclerView2.adapter = adapter2.withLoadStateHeader(
//            footer = PagerFooterAdapter(),
            header = headerAdapter2
        )
//        binding.emptyLayout2.setOnClickListener {
//            adapter2.refresh()
//            getCateData()
//
//        }
        binding.refreshLayout2.setOnRefreshListener {
            adapter2.refresh()
            getCateData()

        }

        lifecycleScope.launch {
            viewModel.pagingDataUser2().collect {
                adapter2.submitData(it)
            }
        }
        val gridLayoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)

        binding.recyclerView2.layoutManager = gridLayoutManager

        viewModel.home2Call.observe(this, Observer {
            it?.let {
                if (it.isSuccess) {
                    headerAdapter2.goodsIndex = it.data!!

                    val list = it.data!!.tj_goods_list as MutableList<GoodsIndex.TjGoods?>
                    if (list.size > 0) {
//                        adapter2.submitData(list, it.data!!)
//                        binding.emptyLayout2.visibility = View.GONE
                    }
                } else {
                    if (adapter2.itemCount == 0) {
//                        binding.emptyLayout2.errorType = EmptyLayout.NETWORK_ERROR
                    }
                }
            }

        })


        initCate()
    }

    var isFloat: Boolean = false //是否处于悬浮状态

    private fun initCate() {
        binding.myScrollView2.setScrollViewListener(object : MyScrollview1.ScrollViewListener {
            override fun onScrollChanged(
                scrollView: MyScrollview1?,
                l: Int,
                t: Int,
                oldl: Int,
                oldt: Int
            ) {
                val recyclerView2 = binding.recyclerView2
                val layout = binding.svLayoutTab20
                val mTabLayout = binding.tabContent2

                val mlLayout2 = binding.svLayoutTab2

                if (t > recyclerView2.height && mTabLayout.parent === layout) {
                    layout.removeView(mTabLayout)
                    mlLayout2.addView(mTabLayout)//
                    mlLayout2.setBackgroundColor(resources!!.getColor(R.color.main_bg))

                    var parentLayout = RelativeLayout(requireContext())
                    setLayoutTabMargin(mlLayout2, parentLayout!!, -10f)
                    isFloat = true

                } else if (t < recyclerView2.height && mTabLayout.parent === mlLayout2) {
                    mlLayout2.removeView(mTabLayout)//
                    layout.addView(mTabLayout)
                    layout.setBackgroundColor(Color.TRANSPARENT)

                    var parentLayout = LinearLayout(requireContext())
                    setLayoutTabMargin(layout, parentLayout!!, 1f)
                    isFloat = false
                }


//                viewModel.cutTab2.observe(this@TabOne2Fragment, Observer {
//
//                    for ((i, v) in binding.tabContent2.children.withIndex()) {
//                        var linearLayout: LinearLayout =
//                            ((binding.tabContent2.getChildAt(i)) as LinearLayout)
//                        var linearLayoutSub = linearLayout.getChildAt(0) as LinearLayout
//
//                        var txtTv: TextView = linearLayoutSub.getChildAt(0) as TextView
//                        var txtTvDesc: TextView = linearLayoutSub.getChildAt(1) as TextView
//                        var vIndicator = linearLayoutSub.getChildAt(2) as ImageView
//
//                        if ("$i".equals(it)) {
//                            v.isSelected = true
//                            onTabSelected(txtTv, txtTvDesc, vIndicator)
//                        } else {
//                            v.isSelected = false
//                            onTabUnselected(txtTv, txtTvDesc, vIndicator)
//                        }
////                        onIndicatorState(txtTv, vIndicator, v.isSelected, isFloat)
//
//                    }
//                })

                //t 滚动的高度
                //解决 SwipeRefreshLayout 与 ScrollView 滑动冲突
                if (t <= 0)
                    binding.refreshLayout2.setEnabled(true);
                else
                    binding.refreshLayout2.setEnabled(false);

            }

        })


        binding.viewPager2.clearOnPageChangeListeners()
        binding.viewPager2.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                selectedTab(position)
//                binding.myScrollView.scrollTo(0, 0);

            }

            override fun onPageScrollStateChanged(state: Int) {
            }
        })

        getCateData()
    }

    private fun selectedTab(position: Int) {
        viewModel.cutTab2.value = "$position"
        binding.viewPager2.resetHeight(position)
    }

    private fun setLayoutTabMargin(layout: HorizontalScrollView, vg: ViewGroup, dpf: Float) {
        val margin = ViewGroup.MarginLayoutParams(layout.layoutParams).apply {
            topMargin = dipToPx(layout.resources, dpf).toInt()
        }


        if (vg is LinearLayout) {
            layout.layoutParams = LinearLayout.LayoutParams(margin)
        } else if (vg is RelativeLayout) {
            layout.layoutParams = RelativeLayout.LayoutParams(margin)
        }
    }

//    private fun onIndicatorState(
//        tv: TextView,
//        vIndicator: View,
//        selected: Boolean,
//        isFloat: Boolean
//    ) {
//        if (selected) {//选中
//            if (isFloat) {//悬浮
//                vIndicator.setBackgroundColor(Color.WHITE)
//            } else {
//                vIndicator.setBackgroundColor(resources!!.getColor(R.color.main_color))
//            }
//            tv.setTextColor(resources!!.getColor(R.color.txt_color))
//
//        } else {
//            if (isFloat) {
//                tv.setTextColor(Color.WHITE)
//            } else {
//                tv.setTextColor(resources!!.getColor(R.color.hint_color))
//            }
//            vIndicator.setBackgroundColor(Color.TRANSPARENT)
//        }
//
//    }

    //得到分类数据
    private fun getCateData() {
        viewModel.callCate2.observe(this, Observer {
            it?.let {
                if (it.isSuccess && it.data != null) {
                    val list: MutableList<CateGoods.TypeInfo>? =
                        it.data?.category_list as MutableList<CateGoods.TypeInfo>?
                    if (list != null && list.size > 0) {
                        pageAdapter2 =
                            CateGoodsPage2Adapter(childFragmentManager, binding.viewPager2, list)
                        binding.tabContent2.removeAllViews()
                        for ((i, a) in list.withIndex()) {
                            val tabBinding = DataBindingUtil.inflate<LayoutCatetabItem2Binding>(
                                LayoutInflater.from(requireContext()),
                                R.layout.layout_catetab_item2,
                                binding.tabContent2,
                                false
                            ).apply {
                                index2 = "${i}"
                                txtTv2.text = a.name
                                tvDesc2.text = a.name_info

                                this.root.setOnClickListener {
                                    binding.viewPager2.setCurrentItem(this.index2!!.toInt(), false)

                                    /*it.isSelected = true
                                    for (v in binding.tabContent.children) {
                                        if (v != it) {
                                            v.isSelected = false
                                        }
                                    }*/
                                }
                                onTabUnselected(txtTv2, tvDesc2, vIndicator2)//默认不选中

                                //隐藏竖条分割线
                                if ((list.size - 1) == i) {
                                    vVerticalLine2.visibility = View.GONE
                                } else {
                                    vVerticalLine2.visibility = View.VISIBLE
                                }

                            }
                            binding.tabContent2.addView(tabBinding.root)


//                            tabBinding.root.setOnClickListener {
//                                binding.viewPager2.setCurrentItem(tabBinding.index2!!.toInt(), false)
//
//                                /*it.isSelected = true
//                                for (v in binding.tabContent.children) {
//                                    if (v != it) {
//                                        v.isSelected = false
//                                    }
//                                }*/
//                            }

                        }
                        binding.viewPager2.adapter = pageAdapter2
                        var index = viewModel.cutTab2.value!!.toInt()
                        if (!viewModel.cateId2.value.isNullOrEmpty()) {
                            for ((i, v) in pageAdapter2.list.withIndex()) {
                                if (v.category_id.equals(viewModel.cateId2.value)) {
                                    index = i
                                    viewModel.cateId2.value = ""
                                    break
                                }
                            }
                        }
                        binding.viewPager2.postDelayed({
                            binding.viewPager2.setCurrentItem(index, false)

                            var linearLayout: LinearLayout =
                                ((binding.tabContent2.getChildAt(index)) as LinearLayout)
                            var linearLayoutSub = linearLayout.getChildAt(0) as LinearLayout

                            var txtTv: TextView = linearLayoutSub.getChildAt(0) as TextView
                            var txtTvDesc: TextView = linearLayoutSub.getChildAt(1) as TextView
                            var vIndicator = linearLayoutSub.getChildAt(2) as ImageView

                            txtTv.isSelected = true
                            onTabSelected(txtTv, txtTvDesc, vIndicator)//默认选中
                        }, 0)//20

//                        binding.emptyLayout2.visibility = View.GONE
                    } else {
//                        binding.emptyLayout2.errorType = EmptyLayout.NETWORK_ERROR
                    }
                } else {
//                    binding.emptyLayout2.errorType = EmptyLayout.NETWORK_ERROR
                }
            }
        })

        viewModel.cutTab2.observe(this@TabOne2Fragment, Observer {

            for ((i, v) in binding.tabContent2.children.withIndex()) {
                var linearLayout: LinearLayout =
                    ((binding.tabContent2.getChildAt(i)) as LinearLayout)
                var linearLayoutSub = linearLayout.getChildAt(0) as LinearLayout

                var txtTv: TextView = linearLayoutSub.getChildAt(0) as TextView
                var txtTvDesc: TextView = linearLayoutSub.getChildAt(1) as TextView
                var vIndicator = linearLayoutSub.getChildAt(2) as ImageView

                if ("$i".equals(it)) {
                    v.isSelected = true
                    onTabSelected(txtTv, txtTvDesc, vIndicator)
                } else {
                    v.isSelected = false
                    onTabUnselected(txtTv, txtTvDesc, vIndicator)
                }
//                        onIndicatorState(txtTv, vIndicator, v.isSelected, isFloat)

            }
        })

        if (!::pageAdapter2.isInitialized && viewModel.callCate2.value == null) {
            viewModel.holdCate2()
        }
    }


    private fun onTabSelected(textView: TextView, tvDesc: TextView, vIndicator: View) {//
        val selectedSize = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_PX,
            30f,
            resources.displayMetrics
        )
//        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, selectedSize);
        textView.setTextColor(resources!!.getColor(R.color.main_color))
        tvDesc.setTextColor(resources!!.getColor(R.color.main_color))
        vIndicator.visibility = View.VISIBLE

    }

    private fun onTabUnselected(textView: TextView, tvDesc: TextView, vIndicator: View) {//
        val selectedSize = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_PX,
            16f,
            resources.displayMetrics
        )
//        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, selectedSize);
        textView.setTextColor(resources!!.getColor(R.color.txt_color))
        tvDesc.setTextColor(resources!!.getColor(R.color.hint_color))
        vIndicator.visibility = View.INVISIBLE
    }


    fun goSearch() {
        startActivity(Intent(requireContext(), SearchActivity::class.java))
    }


}

